<?php

namespace App\Repositories\Eloquent;

use App\Models\RulePolicy;
use App\Models\RulePolicyFlight;
use App\Repositories\Contracts\RulePolicyFlightInterface;
use MakeRep\Repository;

class RulePolicyFlightRepository extends Repository implements RulePolicyFlightInterface
{

    public $fillable = [
        'id','admin_id','policy_id','policy_code','platform','airline','way','flight_date','sale_date','cabin','status','commision'
    ];

    function model()
    {
        return RulePolicyFlight::class;
    }

    /**
     * 添加航班
     * @param $param
     * @param $policyId
     * @return void
     */
    public function create($param,$policyId){

        $this->delete(['policy_id'=>$policyId]);

        if (!empty($param['SaleFlightList'])) {

           $this->insertOrUpdate(1,1,$param['SaleFlightList'],$policyId);
        }

        if (!empty($param['SaleLimit'])) {

            $this->insertOrUpdate(1,2,$param['SaleLimit'],$policyId);
        }

        if (!empty($param['BackFlightSale'])) {

            $this->insertOrUpdate(2,1,$param['BackFlightSale'],$policyId);
        }

        if (!empty($param['BackSaleLimit'])) {

            $this->insertOrUpdate(2,2,$param['BackSaleLimit'],$policyId);
        }
    }

    public function insertOrUpdate($way,$type,$flights,$policyId){

        $data = [];
        foreach ($flights as $key=>$value){

            $data[] = [
                'policy_id'         => $policyId,
                'way'               => $way,
                'type'              => $type,
                'depart_city_code'  => $value['DPort'],
                'arrived_city_code' => $value['APort'],
                'flight_start'      => $value['FlightFrom'],
                'flight_end'        => $value['FlightTo']
            ];
        }

        $this->insert($data);

    }

}